class Solution {
    public int minOperations(int[] nums, int x) {
        int sum = sum(nums);
        // if(sum < x ){
        //     return -1;
        // }
        int add =0;
        int left = 0 ,right = 0, target = sum -x,
        len =-1; //非常巧妙
       
        while(right <nums.length){
            add+=nums[right];
            while( left < nums.length &&add > target){
                add -= nums[left];
                left ++;
            }
            if(add == target){
                len = Math.max(len , right- left +1);
            
            }
            right++;
        }
        if(len == -1){
            return -1;
        }
        return nums.length-len;
    }
    public int sum(int[] nums){
        int sum = 0;
        for(int i = 0; i < nums.length;i++){
            sum+=nums[i];


        }
        return sum;
    }


    public int minOperation2(int[] nums, int x) {
        int sum = sum(nums);
        if(sum < x ){
            return -1;
        }
        int add =0;
        int left = 0 ,right = 0, target = sum -x,
                len =-1; //非常巧妙

        while(right <nums.length){
            add+=nums[right];
            while( add > target){
                add -= nums[left];
                left ++;
            }
            if(add == target){
                len = Math.max(len , right- left +1);

            }
            right++;
        }
        if(len == -1){
            return -1;
        }
        return nums.length-len;

    }
   
}